package com.szpt.mo.bhubackground.util.config;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import org.springframework.boot.SpringBootConfiguration;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
    //秘钥
    private static final String TOKEN = "xpp@ll";

    /**
     * 生成token(head.playload.sing)
     *
     * @param map 用户传过了的信息，例如id等
     * @return
     */
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        //设置默认7天过期
        instance.add(Calendar.DATE, 7);



        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        //指定令牌过期时间
        String token = builder.withExpiresAt(instance.getTime())
                //sign，传入加密盐
                .sign(Algorithm.HMAC256(TOKEN));
        return token;
    }

    /**
     * 验证token合法性
     *
     * @param token
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    /**
     * 获取token信息方法
     *
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
        return verify;
    }

    /**
     * 获取token payload信息方法
     *
     * @param token
     * @return payload
     */
    public static JWTPayload getTokenPayload(String token) throws JsonProcessingException {
        String payload = getTokenInfo(token).getPayload();
        //base64  to String  {"mail":"2697861661@qq.com","id":"2","exp":1649492366}
        String s = new String(Base64.getDecoder().decode(payload));
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectReader objectReader = objectMapper.readerFor(JWTPayload.class);
        JWTPayload o = objectReader.readValue(s);
        return o;
    }

    public static JWTPayload getTokenPayload(HttpServletRequest request) throws JsonProcessingException {
        return getTokenPayload(request.getHeader("Authorization"));
    }

}
